package operation;

import JDBC.JDBCUtils;
import Medicine.Pharmacy;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class FindPoint implements IOPeration{
    @Override
    public void work(Pharmacy pharmacy) throws SQLException {

        //创建QueryRunner对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        String user = getCurrentUser();

        Integer point = getCurrentUserPoints(user, qr);
        System.out.println("当前积分为" + point);

    }
    public static String getCurrentUser() throws SQLException {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        Scanner sc = new Scanner(System.in);
        System.out.println("确认您的用户账号");
        String user = sc.nextLine();

        int flag = 0;
        String query = "SELECT user FROM buyman";
        List<Map<String, Object>> equipmentList = qr.query(query, new MapListHandler());
        for (Map<String, Object> equipmentMap : equipmentList) {
            if (equipmentMap.get("user").equals(user)) {
                flag = 1;
                break;
            }
        }
        if(flag == 0){
            System.out.println("输入有误或该用户不存在");
        }
        return user;
    }
    private int getCurrentUserPoints(String user, QueryRunner qr) throws SQLException {
        String query = "SELECT point FROM buyman WHERE user=?";
        ScalarHandler<Integer> sh = new ScalarHandler<>();
        return qr.query(query, sh, user);
    }
}
